package com.kay.car.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kay.car.dao.PriceDao;
import com.kay.car.entity.PriceTable;
import com.kay.car.util.DataUtil;
import com.kay.car.util.HttpUtil;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PriceService {
    @Autowired
    private PriceDao priceDao;

    public void spider() {
        System.out.println("开始爬取");
        HashMap<String,String> searchMap = new HashMap<>();
        searchMap.put("polo","dazhong-polo");
        searchMap.put("高尔夫","golf");
        searchMap.put("宝来","baolai");
        searchMap.put("朗逸","langyi");
        searchMap.put("速腾","suteng");

        HashMap<String, String> header = new HashMap<>();
        header.put("Host", "m.guazi.com");
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0");
        header.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        header.put("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        header.put("Accept-Encoding", "gzip, deflate, br");
        header.put("Connection", "keep-alive");
        header.put("Cookie", "uuid=6a2eaff4-f22e-42bc-fbb0-22221549c204; tktrackid=348943046042058752; cainfo=%7B%22ca_s%22%3A%22seo_baidu%22%2C%22ca_n%22%3A%22default%22%2C%22ca_medium%22%3A%22-%22%2C%22ca_term%22%3A%22-%22%2C%22ca_content%22%3A%22-%22%2C%22ca_campaign%22%3A%22-%22%2C%22ca_kw%22%3A%22%25e7%2593%259c%25e5%25ad%2590%25e4%25ba%258c%25e6%2589%258b%25e8%25bd%25a6%22%2C%22ca_i%22%3A%22-%22%2C%22scode%22%3A%22-%22%2C%22guid%22%3A%226a2eaff4-f22e-42bc-fbb0-22221549c204%22%2C%22keyword%22%3A%22-%22%2C%22ca_keywordid%22%3A%22-%22%2C%22display_finance_flag%22%3A%22-%22%2C%22platform%22%3A%222%22%2C%22version%22%3A1%2C%22client_ab%22%3A%22-%22%2C%22sessionid%22%3A%22302273f4-5cbe-4955-fa8c-d12b7caf3578%22%2C%22ca_a%22%3A%22-%22%2C%22ca_b%22%3A%22-%22%7D; sessionid=302273f4-5cbe-4955-fa8c-d12b7caf3578; guazitrackersessioncadata=%7B%22ca_kw%22%3A%22%25e7%2593%259c%25e5%25ad%2590%25e4%25ba%258c%25e6%2589%258b%25e8%25bd%25a6%22%2C%22ca_a%22%3A%22-%22%7D; cityDomain=qd; user_city_id=114; preTime=%7B%22last%22%3A1629468218%2C%22this%22%3A1629466957%2C%22pre%22%3A1629466957%7D; __utmganji_v20110909=6e8d64d0-b935-4247-8672-f281febfa972; Hm_lvt_bf3ee5b290ce731c7a4ce7a617256354=1629466960; Hm_lpvt_bf3ee5b290ce731c7a4ce7a617256354=1629468220; gr_user_id=cb36c036-52ab-4d7f-b1b0-244ae54388b1; gr_session_id_bf5e6f1c1bf9a992=aab845ea-8163-4e18-8395-eb7d7c051dcb; gr_session_id_bf5e6f1c1bf9a992_aab845ea-8163-4e18-8395-eb7d7c051dcb=true; cityGuideInfo=2021-8-20%231; tracker_session={%22ca_a%22:%22-%22%2C%22ca_b%22:%22-%22}");
        header.put("Upgrade-Insecure-Requests", "1");
        header.put("Sec-Fetch-Dest", "document");
        header.put("Sec-Fetch-Mode", "navigate");
        header.put("Sec-Fetch-Site", "none");
        header.put("Sec-Fetch-User", "?1");
        header.put("Pragma", "no-cache");
        header.put("Cache-Control", "no-cache");
        header.put("TE", "trailers");

        for (String searchKey:searchMap.keySet()) {
            int page = 0;
            HashMap<String,HashMap<String,HashMap<String,HashMap<String,ArrayList<Double>>>>> keyMap = new HashMap<>();
            while(true) {
                page++;
                JSONArray data = JSONObject.parseObject(HttpUtil.get("https://m.guazi.com/qd/"+searchMap.get(searchKey)+"/o"+page+"/", "act=getNext")).getJSONArray("data");
                System.out.println(data.toJSONString());
                if(data.size()==0) {
                    System.out.println("最大页数:"+(page-1));
                    break;
                }
                for (int i = 0; i < data.size(); i++) {
                    JSONObject obj = data.getJSONObject(i);
                    String title = obj.getString("title");
                    String[] infos = title.split(" ");
                    String year = "";
                    String output = "";
                    String type = "自动";
                    for (String info:infos) {
                        if(info.contains("款")&&info.length()>4){
                            year = info.substring(info.indexOf("款")-4,info.indexOf("款"));
                        }
                        if(info.contains(".")){
                            output = info.replace("TSI","T");
                        }
                        if(info.contains("手动")){
                            type = "手动";
                        }
                    }
                    if(output.equals("")){
                        if(title.contains("200TSI")) {
                            output = "1.2T";
                        }else if(title.contains("230TSI")){
                            output = "1.4T";
                        }else if(title.contains("280TSI")){
                            output = "1.4T";
                        }
                    }
                    output = output.replace("L","").replace("T","");
                    if(output.equals("")){
                        System.out.println("????"+obj.toJSONString());
                    }
                    double price = Double.parseDouble(Jsoup.parse(obj.getString("display_price")).getElementsByTag("i").text().replace("万",""));
                    if(keyMap.get(searchKey) == null){
                        keyMap.put(searchKey,new HashMap<>());
                    }
                    HashMap<String, HashMap<String, HashMap<String, ArrayList<Double>>>> yearMap = keyMap.get(searchKey);

                    if(yearMap.get(year) == null){
                        yearMap.put(year,new HashMap<>());
                    }
                    HashMap<String, HashMap<String, ArrayList<Double>>> outputMap = yearMap.get(year);

                    if(outputMap.get(output) == null){
                        outputMap.put(output,new HashMap<>());
                    }
                    HashMap<String, ArrayList<Double>> typeMap = outputMap.get(output);

                    if(typeMap.get(type) == null){
                        typeMap.put(type,new ArrayList<Double>());
                    }
                    typeMap.get(type).add(price);
                }
            }

            for (String key:keyMap.keySet()) {
                for (String year:keyMap.get(key).keySet()) {
                    for (String output:keyMap.get(key).get(year).keySet()){
                        for (String type:keyMap.get(key).get(year).get(output).keySet()) {
                            ArrayList<Double> list = keyMap.get(key).get(year).get(output).get(type);
                            Double[] data = list.toArray(new Double[list.size()]);
                            System.out.println(JSONObject.toJSONString(data));
                            JSONObject json = DataUtil.getPrice(data);
                            PriceTable priceTable = priceDao.findOneByKeywordAndYearAndOutputAndType(key,year,output,type);
                            if(priceTable==null){
                                priceTable = new PriceTable();
                            }
                            priceTable.setKeyword(key);
                            priceTable.setYear(year);
                            priceTable.setOutput(output);
                            priceTable.setType(type);
                            priceTable.setPrice(json.getFloatValue("price"));
                            priceTable.setCount(json.getIntValue("count"));
                            priceTable.setUpdateTime(new Date());
                            System.out.println(JSONObject.toJSONString(priceTable));
                            priceDao.save(priceTable);
                        }
                    }
                }
            }
        }
    }

    public List<PriceTable> getPriceAll(String key) {
        List<PriceTable> pricelist;
        if(key.equals("")){
            pricelist = priceDao.findAll();
        }else{
            pricelist = priceDao.findAllByKeywordOrderByYearDesc(key);
        }
        return pricelist;
    }

    public void deleteOld() {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, -7);
        priceDao.deleteAllByUpdateTimeBefore(cal.getTime());
    }
}
